package com.example.myapplication.Student;

import android.content.Context;
import android.content.Intent;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.myapplication.AbsFragment.Home;
import com.example.myapplication.Adapter.CourseAdapter;
import com.example.myapplication.Data.Course;
import com.example.myapplication.Data.CourseData;
import com.example.myapplication.Data.UserData;
import com.example.myapplication.R;
import com.example.myapplication.Teacher.Tea_MyDetailActivity;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class StudentCourse extends Home {
    private UserData userData;
    private int id;
    private JsonObject jsonObject;
    private CourseData courseData;//用于接收请求数据
    private CourseAdapter adapter;
    private ListView lvCourseList;//适配器显示视图
    private List<Course> courses;
    private final Gson gson = new Gson();
    //请求数据
    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据
    private Context mContext;
    private int roleId;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_student_course;
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }

    public void get(){
        new Thread(() -> {
            userData = (UserData)getActivity().getIntent().getSerializableExtra("userData");
            roleId = userData.getRoleId();
            id = userData.getId();
            // url路径
            String url = "http://47.107.52.7:88/member/sign/course/student?"
                    +"userId="+id;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            handleResponse();
        }
    };

    private void handleResponse() {
        if (code == 200) {
            // 请求成功
            if (data != null) {

                jsonObject = gson.toJsonTree(data).getAsJsonObject();
                courseData = gson.fromJson(jsonObject, CourseData.class);
                courses = courseData.getRecords();

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                    }
                });
                // 遍历课程列表，查看数据是否准确
                for (Course course : courses) {
                    String courseId = course.getCourseId();
                    String courseName = course.getCourseName();
                    String coursePhoto = course.getCoursePhoto();
                    String collegeName = course.getCollegeName();

                    Log.d("Course Info", "Course ID: " + courseId);
                    Log.d("Course Info", "Course Name: " + courseName);
                    Log.d("Course Info", "Course Photo URL: " + coursePhoto);
                    Log.d("Course Info", "College Name: " + collegeName);
                }

            }
        } else {
            // 请求失败
            if (msg != null) {
                Log.d("请求失败", msg);
            }
        }
    }
    public void initData() {
        lvCourseList=(ListView)getActivity().findViewById(R.id.unfinished_list_view);
        lvCourseList.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Course clickedItem = courses.get(i);
                        Intent intent = new Intent();
                        Log.d("roleId", String.valueOf(roleId));
                        if(roleId == 1) {
                            intent.setClass(getActivity(), Tea_MyDetailActivity.class);
                        } else if(roleId == 0) {
                            intent.setClass(getActivity(), Stu_MyDetailActivity.class);
                        } else {
                            Log.d("跳转失败失败", "身份认证出错  ");
                        }

                        // 将被点击项的数据传递给下一个活动
                        intent.putExtra("courseData", clickedItem);
                        intent.putExtra("userData", userData);

                        startActivity(intent);
                    }
                    }
        );
        adapter = new CourseAdapter( getActivity(),
                R.layout.list_item_course, courses);
        lvCourseList.setAdapter(adapter);
        Refresh();
    }
    //刷新
    public void Refresh() {
        //刷新列表
        SwipeRefreshLayout swipeRefreshLayout = getActivity().findViewById(R.id.swipeRefreshLayout_stu_course);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                get();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
}

